package com.wuyan.wurpc.bootstrap;

import com.wuyan.wurpc.RpcApplication;
import com.wuyan.wurpc.config.RegistryConfig;
import com.wuyan.wurpc.config.RpcConfig;
import com.wuyan.wurpc.model.ServiceMetaInfo;
import com.wuyan.wurpc.model.ServiceRegisterInfo;
import com.wuyan.wurpc.registry.LocalRegistry;
import com.wuyan.wurpc.registry.Registry;
import com.wuyan.wurpc.registry.RegistryFactory;
import com.wuyan.wurpc.server.tcp.VertxTcpServer;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

@Slf4j
public class ProviderBootstrap {

    public static void init(List<ServiceRegisterInfo<?>> serviceRegisterInfoList) {

        //RPC框架初始化
        log.info("1. 框架初始化");
        RpcApplication.init();
        //全局配置
        final RpcConfig rpcConfig = RpcApplication.getRpcConfig();
        log.info("全局配置RpcConfig : " + rpcConfig);
        //注册服务
        log.info("2. 注册服务");
        for(ServiceRegisterInfo<?> serviceRegisterInfo : serviceRegisterInfoList) {
            String serviceName = serviceRegisterInfo.getServiceName();
            //本地注册
            LocalRegistry.register(serviceName, serviceRegisterInfo.getImplClass());
            //注册服务到注册中心
            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(serviceName);
            serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());
            serviceMetaInfo.setServicePort(rpcConfig.getServerPort());
            log.info("注册服务：serviceMetaInfo : {}", serviceMetaInfo);
            try{
                registry.register(serviceMetaInfo);
            }catch (Exception e){
                throw new RuntimeException(serviceName + "服务注册失败", e);
            }
        }

        //启动服务器
        log.info("3. 启动服务器");
        VertxTcpServer vertxTcpServer = new VertxTcpServer();
        vertxTcpServer.doStart(rpcConfig.getServerPort());
    }


}
